// MouseMage, a rodent behavioral data collection and analysis program for Android devices.
// Copyright (C) 2012 Joseph Van Swearingen
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

package com.zythran.mousemage;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.TextView;
import android.text.format.Time;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;

public class StartScreenActivity extends Activity implements View.OnClickListener, OnItemSelectedListener, DialogInterface.OnClickListener {
	private SharedPreferences settings ;
	
	int num_timepoints ;
	int num_animals ;
	int num_bins ;
	int protocol ;
	String start_text ;
	
	Button more_timepoints_btn ;
	Button fewer_timepoints_btn ;
	Button more_bins_btn ;
	Button fewer_bins_btn ;
	Button more_animals_btn ;
	Button fewer_animals_btn ;
	Button clear_settings_btn ;
	Button begin_test_btn ;
	//Button restore_prev_btn ;
	
	TextView timepoints_txt ;
	TextView bins_txt ;
	TextView animals_txt ;
	
	EditText test_text ;
    Spinner proto_spinner ;
	boolean start_screen_modified ;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.intro);
        
        start_screen_modified = false ;
        
        boolean started = false ;
        num_timepoints = 12 ;
        num_animals = 8 ;
        num_bins = 2 ;
        
        settings = getSharedPreferences("MouseMagePrefs", MODE_PRIVATE );
        start_screen_modified = settings.getBoolean("start_screen_modified", false) ;
        started = settings.getBoolean("started", false) ;
        
        SharedPreferences.Editor ed = settings.edit();
        ed.putBoolean("reload_from_file", false) ;
        ed.commit() ;

        if (started) {
        	// skip this screen and go to the main program
        	Intent myIntent = new Intent(this, MouseMageActivity.class) ;
        	//myIntent.putExtra("starting", false);
        	startActivityForResult(myIntent, 0); 
        } else if (start_screen_modified) {
        	num_timepoints = settings.getInt("num_timepoints", 12) ;
        	num_animals = settings.getInt("num_animals", 8) ;
        	num_bins = settings.getInt("num_bins", 2) ;
        	protocol = settings.getInt("protocol", 1) ;
        	start_text = settings.getString("start_notes_txt", "") ;
        }
        
        more_timepoints_btn= (Button) findViewById(R.id.more_timepoints_btn) ;
        fewer_timepoints_btn= (Button) findViewById(R.id.fewer_timepoints_btn) ;
        more_animals_btn= (Button) findViewById(R.id.more_animals_btn) ;
        fewer_animals_btn= (Button) findViewById(R.id.fewer_animals_btn) ;
        more_bins_btn= (Button) findViewById(R.id.more_bins_btn) ;
        fewer_bins_btn= (Button) findViewById(R.id.fewer_bins_btn) ;
        clear_settings_btn = (Button) findViewById(R.id.clear_settings_btn) ;
        begin_test_btn = (Button) findViewById(R.id.begin_test_btn) ;
        //restore_prev_btn = (Button) findViewById(R.id.restore_prev_btn) ;
        test_text = (EditText) findViewById(R.id.test_text) ;
                
        more_timepoints_btn.setOnClickListener(this) ;
        fewer_timepoints_btn.setOnClickListener(this) ;
        more_animals_btn.setOnClickListener(this) ;
        fewer_animals_btn.setOnClickListener(this) ;
        more_bins_btn.setOnClickListener(this) ;
        fewer_bins_btn.setOnClickListener(this) ;
        clear_settings_btn.setOnClickListener(this) ;
        begin_test_btn.setOnClickListener(this) ;
        //restore_prev_btn.setOnClickListener(this) ;
        
        timepoints_txt = (TextView) findViewById(R.id.timepoints_txt) ;
        animals_txt = (TextView) findViewById(R.id.animals_txt) ;
        bins_txt = (TextView) findViewById(R.id.bins_txt) ;
        
        proto_spinner = (Spinner) findViewById(R.id.protocol_spinner) ;
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this, R.array.protocol_array, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        proto_spinner.setAdapter(adapter);
        proto_spinner.setOnItemSelectedListener(this);
        proto_spinner.setSelection(1) ;
        
        //String FILE_NAME = "restore_file.dat" ;
        //File file = getFileStreamPath(FILE_NAME);
        //if (!file.exists()) {
       	//	restore_prev_btn.setEnabled(false) ;
        //} else {
        //	restore_prev_btn.setEnabled(true) ;
        //}

    }
    @Override
    public void onPause() {
    	super.onPause() ;
    	SharedPreferences.Editor ed = settings.edit() ;
    	String test_txt = test_text.getText().toString() ;
    	
    	if (start_screen_modified || !test_txt.isEmpty()) {
    	
    		start_screen_modified = true ;
    		ed.putString("start_notes_txt", test_txt) ;
    	
    		ed.putInt("num_timepoints", num_timepoints) ;
			ed.putInt("num_bins", num_bins) ;
			ed.putInt("num_animals", num_animals) ;
			ed.putInt("protocol", protocol) ;
			ed.putBoolean("start_screen_modified", start_screen_modified) ;
			ed.commit() ;
    	}
    }
    public void onClick(View v) {
    	SharedPreferences.Editor ed = settings.edit() ;
    	Intent myIntent ;
    	
    	switch (v.getId()) {
    		case R.id.more_timepoints_btn:
    			num_timepoints++ ;
    			timepoints_txt.setText(""+num_timepoints) ;
    			start_screen_modified = true ;
    			break ;
    			
    		case R.id.fewer_timepoints_btn:
    			if (num_timepoints > 1) {
    				num_timepoints-- ;
    				timepoints_txt.setText(""+num_timepoints) ;
    			}
    			start_screen_modified = true ;
    			break; 

    		case R.id.more_animals_btn:
    			num_animals++ ;
    			animals_txt.setText(""+num_animals) ;
    			start_screen_modified = true ;
    			break ;
    			
    		case R.id.fewer_animals_btn:
    			if (num_animals > 1) {
    				num_animals-- ;
    				animals_txt.setText(""+num_animals) ;
    			}
    			start_screen_modified = true ;
    			break;
    			
    		case R.id.more_bins_btn:
    			num_bins++ ;
    			bins_txt.setText(""+num_bins) ;
    			start_screen_modified = true ;
    			break ;
    			
    		case R.id.fewer_bins_btn:
    			if (num_bins > 1) {
    				num_bins-- ;
    				bins_txt.setText(""+num_bins) ;
    			}
    			start_screen_modified = true ;
    			break;
    			
    		case R.id.clear_settings_btn:

    	        num_timepoints = 12 ;
    	        num_animals = 8 ;
    	        num_bins = 2 ;
    	        timepoints_txt.setText(""+num_timepoints) ;
    	        animals_txt.setText(""+num_animals) ;
    	        bins_txt.setText(""+num_bins) ;
    	        test_text.setText("") ;
    	        start_screen_modified = false ;
    	        proto_spinner.setSelection(1) ;
    			break ;
    			
    		case R.id.begin_test_btn:
    			myIntent = new Intent(this, MouseMageActivity.class) ;
    			//myIntent.putExtra("starting", true);
    			//myIntent.putExtra("num_timepoints", num_timepoints) ;
    			//myIntent.putExtra("num_bins", num_bins) ;
    			//myIntent.putExtra("num_animals", num_animals) ;
    			//myIntent.putExtra("protocol", protocol) ;
    			
    			String test_txt = test_text.getText().toString() ;
    			ed.putString("start_notes_txt", test_txt) ;
    			ed.putBoolean("started", false) ;
    			ed.commit() ;
    			//myIntent.putExtra("start_notes_txt", test_txt) ;
    			
    			// tell the application that it should resume at the 2nd screen
    			
    			v.getContext().startActivity(myIntent); 
    			break ;
    			
//    		case R.id.restore_prev_btn:
//    			// Reload saved temporary values from internal memory
//    			myIntent = new Intent(this, MouseMageActivity.class) ;
//    			ed.putBoolean("reload_from_file", true) ;
//    			ed.commit() ;
//    			v.getContext().startActivity(myIntent) ;
//    			break ;
    	}
    }
    


    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
       	protocol = pos ;
		start_screen_modified = true ;
        //Toast.makeText(parent.getContext(), "The protocol is " +
        //     parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
    }
	public void onNothingSelected(AdapterView<?> parent) {
		// Do nothing	
	}
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.start_scrn_menu, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	SharedPreferences.Editor ed = settings.edit() ;
    	Intent myIntent ;
    	
        // Handle item selection
        switch (item.getItemId()) {
        
        	case R.id.restore_menu_item :
        		// Check whether the file exists, if not, we cannot restore
        		String FILE_NAME = "restore_file.dat" ;
        		File file = getFileStreamPath(FILE_NAME);
        		if (!file.exists()) {
        			Toast.makeText(
        				getApplicationContext(),
        				"No restore file available",
        				Toast.LENGTH_LONG
        			).show();
        		} else {
        			// Reload saved temporary values from internal memory
        			myIntent = new Intent(this, MouseMageActivity.class) ;
        			ed.putBoolean("reload_from_file", true) ;
        			ed.commit() ;
        			startActivity(myIntent) ;
        		}
        		return true ;
        		
        	case R.id.recover_file_item :
        		copy_file() ;
        		return true ;
        		
        	case R.id.help_menu_item :
        		return true ;
        		
        	case R.id.about_menu_item :
        		AlertDialog alertDialog;
        		AlertDialog.Builder builder = new AlertDialog.Builder(this) ;
        		builder.setTitle("About");
        		builder.setMessage("(c) 2012 Joseph Van Swearingen");
        		builder.setPositiveButton("License", this) ;
        		builder.setNegativeButton("Back", this) ;      		
        		
        		alertDialog = builder.create();
        		alertDialog.show();
        		return true ;
        		
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    protected void copy_file() {
    	// backup the file to SD
    	String FILE_NAME = "restore_file.dat" ;
    	File file = getFileStreamPath(FILE_NAME) ;
    	
        Time today = new Time(Time.getCurrentTimezone());
        today.setToNow();
        String date = "" + today.year + "_" + (today.month+1) + "_" + today.monthDay ;

    	
        File storage_dir = Environment.getExternalStorageDirectory() ;
        Log.i("WRITEINFO", "Storage dir = " + storage_dir.getAbsolutePath()) ;
    	File dir = new File(storage_dir, File.separator + "MouseMage" + File.separator + date ) ;
    	Log.i("WRITEINFO", "Creating dir " + dir.getAbsolutePath()) ;
    	dir.mkdirs() ;
    	
    	File outfile = new File(dir, File.separator + FILE_NAME) ;
    	
    	if (!file.exists()) {
    		Toast.makeText(
    			getApplicationContext(),
    			"No restore file available",
    			Toast.LENGTH_LONG
    		).show();
    	} else {
    		FileInputStream fis = null ;
    		BufferedReader br = null ;
    		BufferedWriter bw  = null ;
    		try {
    			fis = openFileInput(FILE_NAME) ;
    			br = new BufferedReader(new InputStreamReader(fis)) ;
    			bw = new BufferedWriter(new FileWriter(outfile)) ;
    			
    			String line ;
    			while ((line = br.readLine()) != null) {
    				bw.write(line) ;
    				bw.newLine() ;
    			}
    			
    			fis.close() ;
    			br.close() ;
    			bw.close() ;
    		} catch (IOException ioe) {
    			Log.e("FWE", "File recovery error: "+ ioe.getLocalizedMessage()) ;		
    		}
    	}
    }
    @Override
	public void onClick(DialogInterface dialog, int which) {

    	if (which == DialogInterface.BUTTON_POSITIVE) {
    		Intent lic_intent = new Intent(Intent.ACTION_VIEW) ;

    		// Create a string of the input and write it to the output
    		InputStream istr = this.getResources().openRawResource(R.raw.gpl);
    	    BufferedReader br = new BufferedReader(new InputStreamReader(istr));
        	String data_stream = null ;
        	
    		String FILENAME = "gpl.txt" ;
        	FileOutputStream fos = null ;
        	boolean file_open = false ;
        	File file_h = getFileStreamPath(FILENAME);

        	try {
        		fos = openFileOutput(FILENAME, Context.MODE_WORLD_READABLE) ;
        		file_open = true ;
        	} catch (FileNotFoundException fnf) {
        		Log.w("FNF", "Internal file not found") ;
        	}
        	if (file_open) {
        		try {
        			while ((data_stream = br.readLine()) != null) {
            			fos.write(data_stream.getBytes()) ;
            			fos.write('\n') ;
            		}
            		br.close() ;
            		istr.close() ;
        			fos.close() ;
        		} catch (IOException ioe) {
        			Log.w("IOE", "Error writing to license file") ;
        		}   		
        	}
    		Uri uri = Uri.fromFile(file_h) ;
    		lic_intent.setDataAndType(uri, "text/plain") ;
    		try {
    			startActivity(lic_intent) ;
    		} catch (ActivityNotFoundException anef) {
    			Log.i("ANF", anef.getLocalizedMessage()) ;
    			Toast.makeText(
    				getApplicationContext(),
    				"No text viewer installed",
    				Toast.LENGTH_LONG
    			).show() ;
    		}
    	} else if (which == DialogInterface.BUTTON_NEGATIVE) {
    		dialog.cancel() ;
    	}
    	
	}
}
